//
//  generalToolBox.m
//  XHYMall
//
//  Created by Assassin on 2019/6/28.
//

#import "generalToolBox.h"
#import <SDAutoLayout.h>
@implementation generalToolBox

#pragma mark xib

//SB中创建VC
+ (UIViewController *) buildVcWithName:(NSString *)name AndId:(NSString *)idStr {
    return [[UIStoryboard storyboardWithName:name bundle:nil] instantiateViewControllerWithIdentifier:idStr];
}

//从Xib中加载一个View
+ (UIView *)buildViewWithName:(NSString *)name AndIndex:(NSInteger)index {
    return [[NSBundle mainBundle] loadNibNamed:name owner:nil options:nil][index];
}

//从Xib中加载一个cell
+ (UITableViewCell *)buildCellWithName:(NSString *)name AndIndex:(NSInteger)index {
    return [[NSBundle mainBundle] loadNibNamed:name owner:nil options:nil][index];
}



+ (UIViewController *)getcurrentVC{
    
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];

    NSAssert(window, @"The window is empty");
    //获取根控制器
    UIViewController* currentVC = window.rootViewController;
    //获取当前页面控制器
     BOOL runLoopFind = YES;
     while (runLoopFind){
           if (currentVC.presentedViewController) {
                  currentVC = currentVC.presentedViewController;
              
           } else if ([currentVC isKindOfClass:[UINavigationController class]]) {
                  UINavigationController* navigationController = (UINavigationController* )currentVC;
                   currentVC = [navigationController.childViewControllers lastObject];
                
            } else if ([currentVC isKindOfClass:[UITabBarController class]]){
                    
                    UITabBarController* tabBarController = (UITabBarController* )currentVC;
                    currentVC = tabBarController.selectedViewController;
                    
             } else {
                   NSUInteger childViewControllerCount = currentVC.childViewControllers.count;
                        if (childViewControllerCount > 0) {
                            currentVC = currentVC.childViewControllers.lastObject;
                              return currentVC;
                            
                         } else {
                                return currentVC;
                             
                         }
                    }
     }
    return currentVC;
}

#pragma mark 正则表达式

+ (BOOL) isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (BOOL) isValidatePhoneNum:(NSString *)mobile {
    //手机号以13,14,15,17,18,19开头，9个 \d 数字字符
//    NSString *phoneRegex = @"(^1[3|4|5|7|8|9][0-9]{9}$)";
    NSString *phoneRegex = @"(^1[0-9]{10}$)";

    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

+ (BOOL) isValidateIdentityCard: (NSString *)identityCard{
    
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

+(BOOL) weakOrStrongPwd:(NSString *)pwdStr {
    NSString *pswdEx =@"^(?=.*\\d.*)(?=.*[a-zA-Z].*).{6,20}$";
    NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pswdEx];
    return [regExPredicate evaluateWithObject:pwdStr];
}

+(BOOL) isValidCardNumber:(NSString *)cardNumber {
    NSString *digitsOnly = [self getDigitsOnly:cardNumber];
    int sum = 0;
    int digit = 0;
    int addend = 0;
    BOOL timesTwo = false;
    for (int i = digitsOnly.length  - 1.0; i >= 0; i--)
    {
        digit = [digitsOnly characterAtIndex:i] - '0';
        if (timesTwo)
        {
            addend = digit * 2;
            if (addend > 9) {
                addend -= 9;
            }
        }
        else {
            addend = digit;
        }
        sum += addend;
        timesTwo = !timesTwo;
    }
    int modulus = sum % 10;
    return modulus == 0;
}

+(NSString *)getDigitsOnly:(NSString*)str{
    NSString *digitsOnly = @"";
    char c;
    for (int i = 0; i < str.length; i++)
    {
        c = [str characterAtIndex:i];
        if (isdigit(c))
        {
            digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
        }
    }
    return digitsOnly;
}

+ (BOOL) isValidPassport:(NSString*)value{
    const char *str = [value UTF8String];
    char first = str[0];
    NSInteger length = strlen(str);
    if (!(first == 'P' || first == 'G'))
    {
        return NO;
    }
    if (first == 'P')
    {
        if (length != 8)
        {
            return NO;
        }
    }
    if (first == 'G')
    {
        if (length != 9)
        {
            return NO;
        }
    }
    BOOL result = YES;
    for (NSInteger i = 1; i < length; i++)
    {
        if (!(str[i] >= '0' && str[i] <= '9'))
        {
            result = YES;
            break;
        }
    }
    return result;
}


#pragma mark 颜色
//将十六进制颜色字符串转化为RGB颜色  colorStr:16进制字符串（可以以0x开头，可以以#开头，也可以就是6位的16进制）
+ (UIColor *)getColorWithHexadecimalColorStr:(NSString *)colorStr {
    
    return [self getColorWithHexadecimalColorStr:colorStr andAlpha:1];
}

+ (UIColor *)getColorWithHexadecimalColorStr:(NSString *)colorStr andAlpha:(float)alpha{
    
    NSString * cString = [[colorStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor clearColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    
    if ([cString length] != 6) return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString * rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString * gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString * bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float)r / 255.0f)
                           green:((float)g / 255.0f)
                            blue:((float)b / 255.0f)
                           alpha:alpha];
}


#pragma mark 字符串
+ (CGSize)sizeForStr:(NSString *)str WithFont:(UIFont * _Nonnull)font maxSize:(CGSize)maxSize {
    
    return [str boundingRectWithSize:maxSize
                             options:NSStringDrawingUsesLineFragmentOrigin
                          attributes:@{NSFontAttributeName : font}
                             context:nil].size;
}

+ (BOOL)isInclucString:(NSString * _Nonnull)mainStr andSubString:(NSString *)subStr {
    
    return [mainStr rangeOfString:subStr].location != NSNotFound;
}


+ (NSString *)getYMDHMSStringFromDateString:(NSString *)timeStampString{
    // timeStampString 是服务器返回的13位时间戳
    // iOS 生成的时间戳是10位 1535558400
    if (timeStampString == nil) {
        return @"";
    }
    NSTimeInterval interval =[timeStampString doubleValue]/1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"] ];
    return [formatter stringFromDate: date];
}

+ (NSString *)getYMDStringFromDateString:(NSString *)timeStampString{
    // timeStampString 是服务器返回的13位时间戳
    // iOS 生成的时间戳是10位 1535558400
    if (timeStampString == nil) {
        return @"";
    }
    NSTimeInterval interval =[timeStampString doubleValue]/1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"] ];
    return [formatter stringFromDate: date];
}

+ (NSString *)timeStampConversion:(NSInteger)time {
    if (time) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time/1000];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *dateShown = [dateFormatter stringFromDate:date];
        return dateShown;
    } else {
        return nil;
    }
}

+(NSString*)getCurrentTimes{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
//    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//    //现在时间,你可以输出来看下是什么格式
//    NSDate *datenow = [NSDate date];
//    //----------将nsdate按formatter格式转成nsstring
//    NSString *currentTimeString = [formatter stringFromDate:datenow];
//    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    NSDate *dateNow = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *timeS = [NSString stringWithFormat:@"%d000", (int)[dateNow timeIntervalSince1970]];
    return timeS;
}

/**
 @method 获取指定宽度width,字符串value的高度
 @param label 待计算的Label
 @result float 返回的高度
 */
+ (float) getHeightForLabelString:(UILabel *)label andWidth:(float)width{
    //获取当前Label的文本的属性
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:label.text];
    label.attributedText = attrStr;
    NSRange range = NSMakeRange(0, attrStr.length);
    // 获取该段attributedString的属性字典
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];
    // 计算文本的大小
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(width - 16.0, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return size.height;
}


+ (CGFloat)getWidthWithText:(NSString *)text height:(CGFloat)height font:(CGFloat)font{
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                     context:nil];
    return rect.size.width;
}


+ (CGFloat)getHeightWithText:(NSString *)text width:(CGFloat)width font:(CGFloat)font{
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                     context:nil];
    return rect.size.height;
}


+ (NSString *) removeWhiteSpaceWithStr:(NSString *)str {
    NSString *resultStr=@"";
    NSArray *arr=[str componentsSeparatedByString:@" "];
    for (NSString *str in arr)
    {
        resultStr = [resultStr stringByAppendingString:str];
    }
    return resultStr;
}

+(BOOL) isEmptyString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+(BOOL)isNumberString:(NSString *)str{
    NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:str];
    if ([numberSet isSupersetOfSet:stringSet])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (BOOL) stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    return returnValue;
}

+ (NSString *) converStrEmoji:(NSString *)emojiStr {
    __block NSString *muStr = [[NSString alloc]initWithString:emojiStr];
    [emojiStr enumerateSubstringsInRange:NSMakeRange(0, emojiStr.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        if ([self stringContainsEmoji:substring]) {
            muStr = [muStr stringByReplacingOccurrencesOfString:substring withString:@""];
        }
    }];
    return muStr;
}

+ (BOOL) isPureChineseCharacters:(NSString *)Str {
    if (Str.length == 0) {
        return NO;
    }
    
    NSString *realNamePattern = @"^[\u4e00-\u9fa5]{0,}";
    NSPredicate *realNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",realNamePattern];
    
    if(![realNamePredicate evaluateWithObject:Str]){
        return NO;
    }else{
        return YES;
    }
}


/// 特殊符号
+ (NSString *)specialSymbolsAction{
    //数学符号
    NSString *matSym = @" ﹢×÷±/=≌∽≦≧≒﹤﹥≈≡≠=≤≥<>≮≯∷∶∫∮∝∞∧∨∑∏∪∩∈∵∴⊥∥∠⌒⊙√∟⊿㏒㏑%‰⅟½⅓⅕⅙⅛⅔⅖⅚⅜¾⅗⅝⅞⅘≂≃≄≅≆≇≈≉≊≋≌≍≎≏≐≑≒≓≔≕≖≗≘≙≚≛≜≝≞≟≠≡≢≣≤≥≦≧≨≩⊰⊱⋛⋚∫∬∭∮∯∰∱∲∳%℅‰‱øØπ";
    
    //标点符号
    NSString *punSym = @"＇：∶；?‘’“”〝〞ˆˇ﹔﹖﹑·¨….¸;！´？！～ˉ｜‖＂〃｀@﹫¡¿﹏﹋﹌︴々﹟#﹩$﹠&﹪%*﹡﹢﹦﹤‐￣¯―﹨ˆ˜﹍﹎+=<＿_ˇ~﹉﹊（）〈〉‹›﹛﹜『』〖〗［］《》〔〕{}「」【】︵︷︿︹︽_﹁﹃︻︶︸﹀︺︾ˉ﹂﹄︼❝❞!():,'[]｛｝^・.·．•＃＾＊＋＝＼＜＞＆§⋯`／|\"\\";
    
    //单位符号＊·
    NSString *unitSym = @"°′″＄￥〒￠￡％＠℃℉﹩﹪‰﹫㎡㏕㎜㎝㎞㏎m³㎎㎏㏄º○¤%$º¹²³";
    
    //货币符号
    NSString *curSym = @"₽€£Ұ₴$₰¢₤¥₳₲₪₵元₣₱฿¤₡₮₭₩ރ円₢₥₫₦zł﷼₠₧₯₨Kčर₹ƒ₸￠";
    
    //制表符
    NSString *tabSym = @"─ ━│┃╌╍╎╏┄ ┅┆┇┈ ┉┊┋┌┍┎┏┐┑┒┓└ ┕┖┗ ┘┙┚┛├┝┞┟┠┡┢┣ ┤┥┦┧┨┩┪┫┬ ┭ ┮ ┯ ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻┼ ┽ ┾ ┿ ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╪ ╫ ╬═║╒╓╔ ╕╖╗╘╙╚ ╛╜╝╞╟╠ ╡╢╣╤ ╥ ╦ ╧ ╨ ╩ ╳╔ ╗╝╚ ╬ ═ ╓ ╩ ┠ ┨┯ ┷┏ ┓┗ ┛┳ ⊥ ﹃ ﹄┌ ╮ ╭ ╯╰";
    
    return [NSString stringWithFormat:@"%@%@%@%@%@",matSym,punSym,unitSym,curSym,tabSym];
}

//去除字符串尾部的零
+(NSString *)removeAllZero:(NSString *)numberStr{
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(numberStr.floatValue)];
    return outNumber;
}

//获取一段字体颜色不一样的富文本
+ (NSMutableAttributedString *)getHighlightAttributeString:(NSString *)text highlightText:(NSString *)highlightText highlightColor:(NSString *)highlightColor{
    NSRange hightlightTextRange = [text rangeOfString:highlightText];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    if (hightlightTextRange.length > 0) {
        [attributeStr addAttribute:NSForegroundColorAttributeName
                             value:[generalToolBox getColorWithHexadecimalColorStr:highlightColor]
                             range:hightlightTextRange];
        [attributeStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13.0f] range:hightlightTextRange];
        return attributeStr;
    }else {
        return [highlightText copy];
    }
}

#pragma mark 视图

+(void)cutTheRoundedForView:(UIView *)view withCornerRadius:(float)radius {
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
}

+(void)setBorderForView:(UIView *)view withBorderWidth:(float)width  withBorderColor:(NSString *)colorStr  withCornerRadius:(float)radius {
    view.layer.borderColor = [self getColorWithHexadecimalColorStr:colorStr].CGColor;
    view.layer.borderWidth = width;
    [self cutTheRoundedForView:view withCornerRadius:radius];
}

+(void)setVcViewAlpha:(UIViewController *)vc withAlpha:(float)alpha{
    vc.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:alpha];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}

+ (UIImage *)getScreenShotForView:(UIView *)view withRect:(CGRect)rect{
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    
    int scale = [UIScreen mainScreen].scale;
    CGRect tempRect = rect;
    tempRect.origin.x *= scale;
    tempRect.origin.y *= scale;
    tempRect.size.width *= scale;
    tempRect.size.height *= scale;
    
    UIGraphicsBeginImageContextWithOptions(tempRect.size, YES, [UIScreen mainScreen].scale);
    
    if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
        //当有些视图使用OpenGL渲染出来的时候，需要使用这个才能截图，否则是空白
        [view drawViewHierarchyInRect:tempRect afterScreenUpdates:YES];
        
    } else {
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return snapshotImage;
}

+ (UIImage *)createQrImageWithInfoString:(NSString*)str {
    
    NSArray *filter = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    
    CIFilter *filterImage = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    [filterImage setDefaults];
    
    
    NSData * dataImage = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    [filterImage setValue:dataImage forKey:@"inputMessage"];
    
    CIImage *outputImage = [filterImage outputImage];
    
    outputImage = [outputImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    
    UIImage *image = [UIImage imageWithCIImage:outputImage];
    
    //    // 为二维码加自定义图片
    //
    //    // 开启绘图, 获取图片 上下文<图片大小>
    //    UIGraphicsBeginImageContext(image.size);
    //    // 将二维码图片画上去
    //    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //    // 将小图片画上去
    //    UIImage *smallImage = [[UIImage alloc]init];
    //    [smallImage drawInRect:CGRectMake((image.size.width - 100) / 2, (image.size.width - 100) / 2, 100, 100)];
    //    // 获取最终的图片
    //    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    //    // 关闭上下文
    //    UIGraphicsEndImageContext();
    //    // 显示
    return image;
}


+ (UIImage *) imageToTransparent:(UIImage*) image{
    // 分配内存
    
    const int imageWidth = image.size.width;
    
    const int imageHeight = image.size.height;
    
    size_t bytesPerRow = imageWidth * 4;
    
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    
    
    // 创建context
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    
    
    
    // 遍历像素
    
    int pixelNum = imageWidth * imageHeight;
    
    uint32_t* pCurPtr = rgbImageBuf;
    
    for (int i = 0; i < pixelNum; i++, pCurPtr++)
        
    {
        
        //        //去除白色...将0xFFFFFF00换成其它颜色也可以替换其他颜色。
        
        //        if ((*pCurPtr & 0xFFFFFF00) >= 0xffffff00) {
        
        //
        
        //            uint8_t* ptr = (uint8_t*)pCurPtr;
        
        //            ptr[0] = 0;
        
        //        }
        
        //接近白色
        
        //将像素点转成子节数组来表示---第一个表示透明度即ARGB这种表示方式。ptr[0]:透明度,ptr[1]:R,ptr[2]:G,ptr[3]:B
        
        //分别取出RGB值后。进行判断需不需要设成透明。
        
        uint8_t* ptr = (uint8_t*)pCurPtr;
        
        if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
            
            //当RGB值都大于240则比较接近白色的都将透明度设为0.-----即接近白色的都设置为透明。某些白色背景具有杂质就会去不干净，用这个方法可以去干净
            
            ptr[0] = 0;
            
        }
        
    }
    
    // 将内存转成image
    
    CGDataProviderRef dataProvider =CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
    
    
    
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight,8, 32, bytesPerRow, colorSpace,
                                        
                                        kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider,
                                        
                                        NULL, true,kCGRenderingIntentDefault);
    
    CGDataProviderRelease(dataProvider);
    
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    
    // 释放
    
    CGImageRelease(imageRef);
    
    CGContextRelease(context);
    
    CGColorSpaceRelease(colorSpace);
    
    return resultUIImage;
    
}

//设置状态栏背景色
+ (void)setStatusBarBackgroundColor:(UIColor *)color {
//    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
//    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
//        statusBar.backgroundColor = color;
//    }
}

+ (void)cutWithView:(UIView *)view topLeftRounded:(CGFloat)topLeftRounded topRightRounded:(CGFloat)topRightRounded bottomRightRounded:(CGFloat)bottomRightRounded bottomLeftRounded:(CGFloat)bottomLeftRounded{

    UIBezierPath* path = [UIBezierPath bezierPath];
    
    // 开始绘画 - 顺时针
    
    //左上
    [path addArcWithCenter:CGPointMake(topLeftRounded, topLeftRounded) radius:topLeftRounded startAngle:M_PI endAngle:M_PI *3/2 clockwise:YES];
    [path addLineToPoint:CGPointMake(view.width - topRightRounded, 0)];
    
    //右上
    [path addArcWithCenter:CGPointMake(view.width - topRightRounded, topRightRounded) radius:topRightRounded startAngle:M_PI *3/2 endAngle:0 clockwise:YES];
    [path addLineToPoint:CGPointMake(view.width, view.height - bottomRightRounded)];
    
    //右下
    [path addArcWithCenter:CGPointMake(view.width - bottomRightRounded, view.height - bottomRightRounded) radius:bottomRightRounded startAngle:0 endAngle:M_PI *1/2 clockwise:YES];
    [path addLineToPoint:CGPointMake(bottomLeftRounded, view.height)];
    
    //左下
    [path addArcWithCenter:CGPointMake(bottomLeftRounded, view.height - bottomLeftRounded) radius:bottomLeftRounded startAngle:M_PI *1/2 endAngle:M_PI clockwise:YES];
    [path addLineToPoint:CGPointMake(0, topLeftRounded)];
    

    CAShapeLayer *maskLayer1 = [[CAShapeLayer alloc] init];
    maskLayer1.frame = view.bounds;
    maskLayer1.path = path.CGPath;
    view.layer.mask = maskLayer1;
}

#pragma mark 时间

+ (NSString *)timeDifferenceWithStartDate:(NSDate *)startDate endDate:(NSDate *)endDate{
    
    NSTimeInterval seconds = [endDate timeIntervalSinceDate:startDate];
    
//    int second = (int)seconds%60;
//    int minute =(int)seconds%3600/60;
//    int house = (int)seconds/3600;
//    int day = (int)seconds/(24 *3600);
    
    int day = (int)seconds/(24 *3600);
    seconds = seconds - day*24*3600;
    
    int house = (int)seconds/3600;
    seconds = seconds - house*3600;
    
    int minute =(int)seconds/60;
    seconds = seconds - minute*60;
    
    int second = (int)seconds%60;
    
    NSString *str;
    if (day != 0) {
        str = [NSString stringWithFormat:@"%d天%d小时%d分",day,house,minute];
        
    }else if (day==0 && house !=0) {
        str = [NSString stringWithFormat:@"%d小时%d分",house,minute];
        
    }else if (day==0 && house==0 && minute!=0) {
        str = [NSString stringWithFormat:@"%d分",minute];
        
    }else{
        str = [NSString stringWithFormat:@"%d秒",second];
        
    }
    
    return str;
}


+ (NSString *)timeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    
    NSInteger start = startTime.length == 13 ? [startTime integerValue]/1000:[startTime integerValue];
    NSInteger end = endTime.length == 13 ? [endTime integerValue]/1000:[endTime integerValue];
    
    
    NSDate *startD =[NSDate dateWithTimeIntervalSince1970:start];
    NSDate *endD =[NSDate dateWithTimeIntervalSince1970:end];
    return [self timeDifferenceWithStartDate:startD endDate:endD];
}


+ (NSString *)timeDifferenceNowWithTargetTime:(NSString *)targetTime;{
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *nowDate = [self getNowDate];
    return [self timeDifferenceWithStartTime:[date stringFromDate:nowDate] endTime:targetTime];
}


+ (NSDate *)getNowDate{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    NSTimeInterval time = [zone secondsFromGMTForDate:date];// 以秒为单位返回当前时间与系统格林尼治时间的差
    return  [date dateByAddingTimeInterval:time];
}


@end
